package com.flyan.game.motafx.core.console;

import javafx.scene.text.Text;

import java.util.LinkedList;

/**
 * 游戏控制台
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/1
 */
public class GameConsole {

    /**
     * 历史最大保存条数
     */
    public static final int MAX_HISTORY_SIZE = 1000;

    private final LinkedList<String> out = new LinkedList<>();

    private Text showText;

    public GameConsole setShowText(Text showText) {
        this.showText = showText;
        return this;
    }

    public void print(String text) {
        output(text);
        showText.setText(generateShowText());
    }

    public void println(String text) {
        output(text + "\n");
        showText.setText(generateShowText());
    }

    private void output(String text) {
        /* 历史已满，清理 */
        if (out.size() >= MAX_HISTORY_SIZE) {
            int removeLen = out.size() - MAX_HISTORY_SIZE + 1;
            for (int i = 0; i < removeLen; i++) {
                out.removeLast();
            }
        }
        out.addFirst(text);
    }

    private String generateShowText() {
        if (out.isEmpty()) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        sb.append(out.getFirst());
        if (out.size() > 1) {
            sb.append(out.get(1));
        }
        return sb.toString();
    }

}
